/*
 * sockets-common.c
 *
 *  Created on: Jun 7, 2012
 *      Author: burek
 */

#include "common-codes.h"
#include "sockets.h"
#include <stdio.h>

int cu_checkIPaddress(const char * address)
{
	int p1 = 256, p2 = 256, p3 = 256, p4 = 256;
	if(sscanf(address, "%d.%d.%d.%d", &p1, &p2, &p3, &p4) != 4)
	{
		return CU_ERROR;
	}
	else
	{
		if(p1 < 0 || p1 > 255 || p2 < 0 || p2 > 255 ||
				p3 < 0 || p3 > 255 || p4 < 0 || p4 > 255)
		{
			return CU_ERROR;
		}
	}
	return CU_OK;
}

void cu_IPtoText(unsigned int ip, char * txt)
{
	unsigned char *parts = (unsigned char *)&ip;
	sprintf(txt, "%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]);
}

int cu_resolveDomainToTxt(const char *dname, char *iptxt)
{
	unsigned int ip = cu_resolveDomain(dname);
	if(ip > 0)
	{
		cu_IPtoText(ip, iptxt);
		return CU_OK;
	}
	else
	{
		return CU_ERROR;
	}
}

unsigned int cu_textToIP(const char * txt)
{
	int p1 = 256, p2 = 256, p3 = 256, p4 = 256;
	if(sscanf(txt, "%d.%d.%d.%d", &p1, &p2, &p3, &p4) != 4)
	{
		return 0;
	}
	else
	{
		if(p1 < 0 || p1 > 255 || p2 < 0 || p2 > 255 ||
				p3 < 0 || p3 > 255 || p4 < 0 || p4 > 255)
		{
			return 0;
		}
		else
		{
			unsigned int ip;
			unsigned char *parts = (unsigned char *)&ip;
			parts[0] = p1;
			parts[1] = p2;
			parts[2] = p3;
			parts[3] = p4;
			return ip;
		}
	}
}
